1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 import java.nio.*;
30 import java.nio.charset.*;
31
32 public class TestISO2022JPSubBytes {
33
34
35
36
37
38 static char[][] in = { {'\u25cb', '\u2460', '\u25cb'},
39 {'\u0061', '\u2460', '\u0061'},
40 {'\u25cb', '\u2460', '\u25cb'},
41 {'\u0061', '\u2460', '\u0061'},
42 };
43 static byte[][] expected = { {0x1b, 0x24, 0x42, 0x21, 0x7b,
44 0x21, 0x29,
45 0x21, 0x7b,
46 0x1b, 0x28, 0x42},
47 {0x61,
48 0x1b, 0x24, 0x42, 0x21, 0x29,
49 0x1b, 0x28, 0x42, 0x61},
50 {0x1b, 0x24, 0x42, 0x21, 0x7b,
51 0x1b, 0x28, 0x42, 0x3f,
52 0x1b, 0x24, 0x42, 0x21, 0x7b,
53 0x1b, 0x28, 0x42},
54 {0x61,
55 0x3f,
56 0x61}
57 };
58
59 public static void main(String args[]) throws Exception {
60 CharsetEncoder enc = Charset.forName("ISO2022JP")
61 .newEncoder()
62 .onUnmappableCharacter(CodingErrorAction.REPLACE);
63
64 test(enc, in[0], expected[0]);
65
66 enc.reset();
67 test(enc, in[1], expected[1]);
68
69 enc.reset();
70 enc.replaceWith(new byte[]{(byte)'?'});
71 test(enc, in[2], expected[2]);
72
73 enc.reset();
74 test(enc, in[3], expected[3]);
75 }
76
77 public static void test (CharsetEncoder enc,
78 char[] inputChars,
79 byte[] expectedBytes) throws Exception
80 {
81 ByteBuffer bb = ByteBuffer.allocate(expectedBytes.length);
82 enc.encode(CharBuffer.wrap(inputChars), bb, true);
83 enc.flush(bb);
84 bb.flip();
85 byte[] outputBuff = bb.array();
86 int outputLen = bb.limit();
87 if (outputLen != expectedBytes.length) {
88 throw new Exception("Output bytes does not match");
89 }
90 for (int i = 0; i < outputLen; ++i) {
91 System.out.printf("<%x:%x> ",
92 expectedBytes[i] & 0xff,
93 outputBuff[i] & 0xff);
94 if (expectedBytes[i] != outputBuff[i]) {
95 System.out.println("...");
96 throw new Exception("Output bytes does not match");
97 }
98 }
99 System.out.println();
100 }
101 }